package logic

import (
	"context"
	"encoding/json"
	"muke/model/mysql"
	"muke/model/redis"
	"muke/mukerpc/internal/svc"
	"muke/mukerpc/mukerpc"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *mukerpc.UserListRequest) (*mukerpc.UserListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	pageSize := in.Size

	if page <= 0 {
		page = 1
	}

	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	var product []mysql.Product

	itoa := strconv.Itoa(int(offset))

	get := redis.Client.Get("productList" + itoa)
	if get.Val() == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Where("name like ?", "%"+in.Name+"%").Order("price desc").Order("created_at desc").Find(&product)

		marshal, _ := json.Marshal(&product)

		redis.Client.Set("productList"+itoa, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
	}
	var productList []*mukerpc.UserList
	for _, m := range product {
		List := &mukerpc.UserList{
			Name:     m.Name,
			Price:    float32(m.Price),
			Img:      m.Img,
			Number:   int64(m.Number),
			Username: m.Username,
		}
		productList = append(productList, List)
	}

	return &mukerpc.UserListResponse{List: productList}, nil
}
